const config = require('../json_api.json');
const jwt = require('jsonwebtoken');

/**
 * @type {import('express').RequestHandler}
 */
 module.exports = (req, res, next) => {
  const { path } = req;
  if (path === '/db') return next();

  const { auth } = config;

  if (!auth.active) {
    return next();
  }

  if (req.header(auth.tokenGenReqHeader)) {
    res.header(auth.tokenResHeader, jwt.sign({}, auth.secret, { expiresIn: auth.expires }))
    return next();
  }

  if (req.header(auth.tokenNotCheckReqHeader)) {
    return next();
  }

  let token = req.header(auth.tokenReqHeader);
  if (!token) return res.status(401).send('invalid token');

  try {
    if (jwt.verify(token.replace(/^Bearer\s/, ''), auth.secret)) {
      next();
    } else {
      res.status(401).send('invalid token');
    }
  } catch(err) {
    res.status(401).send('invalid token');
  }
};
